<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Title</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="/res/plugin/materialize/css/materialize.min.css">


</head>
<body>

<div class="row">
  <div class="col s4">
    <label for="start_day" class="">起始日期</label>
    <input id="start_day" type="date" class="datepicker">
  </div>
  <div class="col s4">
    <label for="end_day" class="">结束日期</label>
    <input id="end_day" type="date" class="datepicker">
  </div>
  <div class="col s4">
    <button id="submit" type="button" class="waves-effect waves-light btn">查询</button>
  </div>
</div>
<div class="row">
  <div id="total_money" class="col s9"></div>
</div>
<div class="row">
  <table class="bordered striped centered">
    <thead>
    <tr>
      <th data-field="id">类别</th>
      <th data-field="name">金额</th>
      <th data-field="price">日期</th>
      <th data-field="remarks">备注</th>
      <th data-field="options">操作</th>
    </tr>
    </thead>
    <tbody id="tbody">

    </tbody>
  </table>

</div>


<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>修改</h4>
    <div class="row">
      <form class="col s12">
        <div class="row">
          <div class="input-field col s12">
            <input id="money" type="number" class="" placeholder="消费金额">
            <label for="money">金额</label>
          </div>
        </div>
        <div class="row">
          <div class="chip-wrapper">
            <div class="chip">5</div>
            <div class="chip">10</div>
            <div class="chip">15</div>
            <div class="chip">25</div>
            <div class="chip">30</div>
            <div class="chip">35</div>
            <div class="chip">40</div>
            <div class="chip">45</div>
            <div class="chip">50</div>
          </div>
        </div>
        <div class="input-field col s12">
          <select id="billType" name="billType">
            <option value="" disabled selected>请选择</option>
            <option value="早餐" data-money="5">早餐</option>
            <option value="中餐" data-money="13">中餐</option>
            <option value="烟" data-money="28">烟</option>
            <option value="晚餐" data-money="16">晚餐</option>
            <option value="其他">其他</option>
          </select>
          <label>消费类型</label>
        </div>
        <div class="row">
          <div class="input-field col s12">
            <textarea id="remarks" class="materialize-textarea"></textarea>
            <label for="remarks">备注</label>
          </div>
        </div>
        <div class="row">
          <div class="input-field col s12">
            <input id="day" name="day" type="date" class="datepicker" value="">
            <label for="day">日期</label>
          </div>
        </div>
      </form>
    </div>
  </div>
  <div class="modal-footer">
    <a href="#!" id="updateBtn" class=" modal-action modal-close waves-effect waves-green btn-flat ">保存</a>
  </div>
</div>



















<script src="/res/plugin/jquery/jquery-3.2.1.min.js"></script>
<script src="/res/plugin/materialize/js/materialize.min.js"></script>
<script src="/res/plugin/layer/layer.js"></script>
<script>
$(function () {
  $('#end_day').val(getDay());
  $('#start_day').val(getDay());
  //初始化
  $('.datepicker').pickadate({
    monthsFull: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthsShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    weekdaysFull: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    weekdaysShort: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    today: '今天',
    clear: '清空',
    'format': 'yyyy-mm-dd',
    firstDay: 0, //星期一作为第一天
    selectMonths: true, // Creates a dropdown to control month
    selectYears: 15 // Creates a dropdown of 15 years to control year
  });
  $('.modal').modal();
  var $money = $('#money');
  var $billType = $('#billType');
  var $day = $('#day');
  $billType.material_select();
  $('.chip-wrapper').on('click', '.chip', function (e, chip) {
    $('#money').val($(this).text());
  });
  $billType.on('change', function (e) {
    if (!$money.val()) {
      let typeMoney = $(this).children('option:selected').attr('data-money');
      $money.val(typeMoney);
    }
  });
  var $id = null;
  $('#updateBtn').on('click', function (e) {
    var money = Number($money.val());
    if (!money > 0) {
      layer.alert('请输入金额');
      return false;
    }
    var billType = $billType.val();
    if (!billType) {
      layer.alert('请选择类别');
      return false;
    }
    let remarks = $('#remarks').val();
    if (billType === '其他' && !remarks) {
      layer.alert('类别为其他时,请输入备注');
      return false;
    }
    let day = $day.val();
    if (!day) {
      layer.alert('请选择日期');
      return false;
    }
    var index = layer.load();
    $fetch('/consume/bill/'+$id, 'put', {
      'money': money,
      'billType': billType,
      'remarks': remarks,
      'day': day,
    }).then((json)=> {
      layer.close(index);
      if (json.result === 1) {
        layer.alert('保存成功');
        searchFunc();
      } else {
        layer.alert(json.msg);
      }
    }).catch(function (err) {
      layer.close(index);
      layer.alert(err);
    });
  });









  $('#submit').on('click', function (e) {
    searchFunc();
  });

  $('table').on('click', '.update', function (e) {
    $('#modal1').modal('open');
    var parentEle = $(this).parent().parent();
    var type = parentEle.children('td').eq(0).html();
    $billType.val(type);
    $billType.material_select();
    var money = parentEle.children('td').eq(1).html();
    $money.val(money);
    var day = parentEle.children('td').eq(2).html();
    $day.val(day);
    var remarks = parentEle.children('td').eq(3).html();
    $('#remarks').val(remarks);
    $id = $(this).attr('data-id');
  })
});
function searchFunc() {
  var search = '';
  var startDay = $('#start_day').val();
  var endDay = $('#end_day').val();
  if(startDay){
    search = 'startDay='+startDay;
  }
  if(endDay){
    if(search!==''){
      search += '&';
    }
    search += 'endDay='+endDay;
  }
  $.get('/consume/bill/getAll?'+search, function (json) {
    if (json.result === 1) {
      var text = '';
      var total = 0;
      json.data.forEach(function (item, index) {
        total += item.money;
        text += `<tr><td>${item.type}</td><td>${item.money}</td><td>${item.day}</td><td>${item.remarks}</td><td><button type="button" class="waves-effect waves-light btn update" data-id="${item._id}">修改</button></td></tr>`;
      })
      $('#tbody').html(text);
      $('#total_money').html('总金额为:'+total);
    } else {
      layer.alert(json.msg);
    }
  });
}
function $fetch(url, type = 'post', body) {
  return new Promise(function(resolve, reject){
    var option = {
      'method': type ,
      'headers': {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      'credentials': 'include',
      //     'body': body?JSON.stringify(body):'',
    };
    if(body && type.toLowerCase()!=='get'){
      option.body = JSON.stringify(body);
    }
    fetch(url, option).then(function (response) {
      if (Math.trunc(response.status / 100) === 2) {  //请求成功
        return response.json();
      } else {
        return Promise.reject(response.statusText);
      }
    }).then(function (result) {
      resolve(result);
    }).catch(function (err) {
      reject(err);
    })
  });
}
function getDay() {
  var date = new Date();
  var text = date.getFullYear() + '-';
  var month = date.getMonth() + 1;
  if (month < 10) {
    text += '0' + month + '-';
  } else {
    text += month + '-';
  }
  var day = date.getDate();
  if (day < 10) {
    text += '0' + day;
  } else {
    text += day;
  }
  return text;
}
</script>
</body>
</html>